//
//  ClassContentViewController.m
//  LiangYa_BObject
//
//  Created by dllo on 15/10/30.
//  Copyright © 2015年 YuHao. All rights reserved.
//

#import "ClassContentViewController.h"
#import "ClassContentData.h"
#import "ClassContentTableViewCell.h"
#import "BuyViewController.h"
#import "ClassCol.h"
#import "CollectHandler.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDKUI.h>

@interface ClassContentViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray *goodDataArr;
@property (nonatomic, strong) UITableView *tableV;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic, assign) NSInteger selectRow;
@property (nonatomic, assign) CGPoint offsetT;
@property (nonatomic, strong) UIView *menuV;
@property (nonatomic, strong) UIImageView *menuCornerIV;
@property (nonatomic, strong) UIButton *menuBtn;
@property (nonatomic, strong) NSDictionary *colDic;
@property (nonatomic, strong) UIButton *colBtn;

@end

@implementation ClassContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.title = self.titleNavi;
    
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"nightstyle"]) {
        self.view.backgroundColor = [UIColor colorWithRed:57/255.0 green:57/255.0 blue:57/255.0 alpha:1];
    }else{
        self.view.backgroundColor = [UIColor whiteColor];
    }
    
    [self dataHandler];
    
    self.tableV = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    _tableV.backgroundColor = [UIColor whiteColor];
    _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableV];
    
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    _HUD.labelText = @"数据加载中...";
    
    self.menuV = [[UIView alloc] init];
    self.menuV.frame = CGRectMake(ScreenWidth - 120, 18 + 64, 110, 100);
    self.menuV.layer.cornerRadius = 10;
    self.menuV.backgroundColor = [UIColor whiteColor];
    
    self.menuCornerIV = [[UIImageView alloc] init];
    self.menuCornerIV.image = [[UIImage imageNamed:@"picture2"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.menuCornerIV.frame = CGRectMake(ScreenWidth - 45, 64, 20, 20);
    self.menuV.hidden = YES;
    self.menuCornerIV.hidden = YES;
    
    
    UIImage *imageM = [[UIImage imageNamed:@"picture.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.menuBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_menuBtn setImage:imageM forState:UIControlStateNormal];
    _menuBtn.frame = CGRectMake(0, 0, 20, 20);
    [_menuBtn addTarget:self action:@selector(menuAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_menuBtn];
    _menuBtn.hidden = YES;
    
    UIButton *button11 = [UIButton buttonWithType:UIButtonTypeSystem];
    button11.frame = CGRectMake(10, 0, 90, self.menuV.bounds.size.height/3-1);
    [button11 setTitleColor:[UIColor blackColor] forState:normal];
    [self.menuV addSubview:button11];
    [button11 setTitle:@"分享" forState:UIControlStateNormal];
    [button11 addTarget:self action:@selector(shareAciton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.colBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _colBtn.frame = CGRectMake(10, self.menuV.bounds.size.height/3, 90, self.menuV.bounds.size.height/3-1);
    [self.menuV addSubview:_colBtn];
    [_colBtn setTitleColor:[UIColor blackColor] forState:normal];
    [_colBtn addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button13 = [UIButton buttonWithType:UIButtonTypeSystem];
    button13.frame = CGRectMake(10, self.menuV.bounds.size.height*2/3, 90, self.menuV.bounds.size.height/3-1);
    [self.menuV addSubview:button13];
    [button13 setTitleColor:[UIColor blackColor] forState:normal];
    [button13 addTarget:self action:@selector(backToTableV) forControlEvents:UIControlEventTouchUpInside];
    [button13 setTitle:@"上划返回列表" forState:UIControlStateNormal];
    
}

- (void)collectAction:(UIButton *)btn
{
    
    self.menuV.hidden = YES;
    self.menuCornerIV.hidden = YES;
    CollectHandler *col = [CollectHandler instandDefault];
    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ClassCol"];
    request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"content contains '%@'", [self.colDic objectForKey:@"content"]]];
    NSArray *colArr = [col.managedObjectContext executeFetchRequest:request error:nil];
    
    if (colArr.count == 0) {
        ClassCol *classcol = [NSEntityDescription insertNewObjectForEntityForName:@"ClassCol" inManagedObjectContext:col.managedObjectContext];
        [classcol setValuesForKeysWithDictionary:self.colDic];
        [col saveContext];
        [self.colBtn setTitle:@"取消收藏" forState:UIControlStateNormal];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:alertAction];
        
        [self presentViewController:alertVC animated:YES completion:^{
            
        }];
        
    }else{
        ClassCol *classCol = [colArr firstObject];
        [col.managedObjectContext deleteObject:classCol];
        [col saveContext];
        [self.colBtn setTitle:@"收藏" forState:UIControlStateNormal];
        
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"取消收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:alertAction];
        
        [self presentViewController:alertVC animated:YES completion:^{
            
        }];
    }
    
}

- (void)shareAciton:(UIButton *)btn
{
    self.menuV.hidden = YES;
    
    self.menuV.hidden = YES;
    NSString *urlString = [self.colDic objectForKey:@"image"];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    NSString *shareStr = [self.colDic objectForKey:@"content"];
    NSString *urlStr = [self.colDic objectForKey:@"buyUrl"];
    //创建分享参数
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:[NSString stringWithFormat:@"分享:<%@> %@",shareStr, urlStr]
                                     images:@[image]
                                        url:url
                                      title:@"分享标题"
                                       type:SSDKContentTypeImage];
    [ShareSDK showShareActionSheet:nil
                             items:nil
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   switch (state) {
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@", error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateCancel:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       default:
                           break;
                   }
                   
                   
               }];

}

- (void)menuAction:(UIButton *)btn
{
    if (self.menuV.hidden) {
        self.menuV.hidden = NO;
        self.menuCornerIV.hidden = NO;
    }else{
        self.menuV.hidden = YES;
        self.menuCornerIV.hidden = YES;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ClassContentData *selectData = [self.goodDataArr objectAtIndex:indexPath.row];
    self.colDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"[%@] ] %@", selectData.brand_name, selectData.style_name], @"brandName", [NSString stringWithFormat:@"%@ %@", selectData.goods_name, selectData.red_title], @"content", [NSString stringWithFormat:@"%@", selectData.imageC], @"image", selectData.price, @"price", selectData.soldNum, @"soleNum", [NSString stringWithFormat:@"%@", selectData.buy_url], @"buyUrl", nil];
    
    CollectHandler *col = [CollectHandler instandDefault];
    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ClassCol"];
    request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"content contains '%@'", [self.colDic objectForKey:@"content"]]];
    NSArray *colArr = [col.managedObjectContext executeFetchRequest:request error:nil];
    
    if (colArr.count == 0) {
        [_colBtn setTitle:@"收藏" forState:UIControlStateNormal];
    }else{
        [_colBtn setTitle:@"取消收藏" forState:UIControlStateNormal];
    }
    
    _menuBtn.hidden = NO;
    tableView.userInteractionEnabled = NO;
    self.offsetT = tableView.contentOffset;
    
    self.selectRow = indexPath.row;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        ClassContentTableViewCell *selectCell = [tableView cellForRowAtIndexPath:indexPath];
        selectCell.frame = CGRectMake(0, 64, ScreenWidth, Screenheight - 64);
        
//        self.navigationController.navigationBar.hidden = YES;
        
        [self.view addSubview:selectCell];
        
        selectCell.isLayout = NO;
        selectCell.backImageV.hidden = NO;
        selectCell.price.hidden = NO;
        selectCell.soldNum.hidden = NO;
        
        CGFloat imageH = selectCell.imageV.image.size.height;
        CGFloat imageW = selectCell.imageV.image.size.width;
        
//        selectCell.imageV.hidden = YES;
        selectCell.imageV.frame = CGRectMake(0, 0, ScreenWidth, ScreenWidth / imageW * imageH);
        selectCell.backImageV.frame = CGRectMake(0, selectCell.imageV.frame.size.height, ScreenWidth, Screenheight - selectCell.imageV.frame.size.height);
        
        
        selectCell.brand_name.font = [UIFont boldSystemFontOfSize:20];
        selectCell.brand_name.textAlignment = NSTextAlignmentLeft;
        selectCell.brand_name.frame = CGRectMake(10, selectCell.backImageV.frame.origin.y + 10, ScreenWidth - 20, 40);
        
        [selectCell.blurV addSubview:selectCell.red_title];
        selectCell.red_title.font = [UIFont boldSystemFontOfSize:17];
        selectCell.red_title.frame = CGRectMake(10, 50, ScreenWidth - 20, Screenheight - 64 - ScreenWidth / imageW * imageH - 150);
        
        selectCell.buyBtn.hidden = NO;
        [self.view addSubview:selectCell.buyBtn];
        selectCell.buyBtn.frame = CGRectMake(ScreenWidth - 100, Screenheight - 60, 80, 40);
        
        [self.view addSubview:selectCell.price];
        selectCell.price.frame = CGRectMake(ScreenWidth - 180, Screenheight - 100, 80, 40);
        
        [self.view addSubview:selectCell.soldNum];
        selectCell.soldNum.frame = CGRectMake(ScreenWidth - 100, Screenheight - 100, 80, 40);
        
        [self.view addSubview:self.menuV];
        [self.view addSubview:self.menuCornerIV];
        
//        selectCell.blackV.hidden = YES;
        selectCell.goods_name.hidden = YES;
        
        // 加手势
        
        selectCell.backImageV.userInteractionEnabled = YES;
        selectCell.imageV.userInteractionEnabled = YES;
        
        UISwipeGestureRecognizer *swipUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(backToTableV)];
        swipUp.direction = UISwipeGestureRecognizerDirectionUp;
        
        [selectCell addGestureRecognizer:swipUp];
        
    }];
    
    
}

- (void)backToTableV
{
    self.menuBtn.hidden = YES;
    self.menuV.hidden = YES;
    self.menuCornerIV.hidden = YES;
    
    self.tableV.userInteractionEnabled = YES;
    
    ClassContentTableViewCell *nowCell = [self.view.subviews objectAtIndex:self.view.subviews.count - 6];
    [self.tableV reloadData];
    self.tableV.contentOffset = self.offsetT;
    [UIView animateWithDuration:0.5 animations:^{
        nowCell.hidden = YES;
        nowCell.goods_name.hidden = NO;
//        nowCell.blackV.hidden = NO;
        [nowCell.imageV addSubview:nowCell.brand_name];
        nowCell.imageV.frame = CGRectMake(0, 0, ScreenWidth, 180);
        nowCell.brand_name.textAlignment = NSTextAlignmentCenter;
        nowCell.brand_name.font = [UIFont systemFontOfSize:15];
        nowCell.brand_name.frame = CGRectMake(0, 90, nowCell.bounds.size.width, 25);
        nowCell.backImageV.hidden = YES;
        [nowCell.blurV addSubview:nowCell.buyBtn];
        nowCell.buyBtn.frame = CGRectMake(ScreenWidth - 100, 130, 80, 40);
        [nowCell.blurV addSubview:nowCell.price];
        nowCell.price.frame = CGRectMake(ScreenWidth - 170, 100, 80, 25);
        [nowCell.blurV addSubview:nowCell.soldNum];
        nowCell.soldNum.frame = CGRectMake(ScreenWidth - 90, 100, 80, 25);
    }];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    ClassContentData *classCD = [self.goodDataArr objectAtIndex:indexPath.row];
//    
//    CGRect rect = [classCD.red_title boundingRectWithSize:CGSizeMake(ScreenWidth - 40, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
//    
//    return rect.size.height + 260;
    
    
    return 180;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    NSLog(@"%ld", _goodDataArr.count);
    return _goodDataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ClassContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"classcontentcell"];
    
    if (!cell) {
        cell = [[ClassContentTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"classcontentcell"];
    }
    
    ClassContentData *classCD = [self.goodDataArr objectAtIndex:indexPath.row];
    
//    cell.goods_name.text = classCD.goods_name;
//    [cell.imageV sd_setImageWithURL:classCD.imageC];
//    cell.brand_name.text = classCD.brand_name;
//    cell.style_name.text = classCD.style_name;
//    cell.red_title.text = classCD.red_title;
//    cell.soldNum.text = classCD.soldNum;
//    cell.price.text = classCD.price;

    // ================================
    
    [cell.backImageV sd_setImageWithURL:classCD.imageC];
    cell.buyBtn.tag = indexPath.row + 100;
    [cell.buyBtn addTarget:self action:@selector(pushBuyVCAction:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.red_title.attributedText = [self shadowstr:[NSString stringWithFormat:@"%@ %@", classCD.goods_name, classCD.red_title]];
    cell.price.attributedText = [self shadowstr:classCD.price];
    cell.soldNum.attributedText = [self shadowstr:classCD.soldNum];
    [cell.imageV sd_setImageWithURL:classCD.imageC placeholderImage:[UIImage imageNamed:@"baikejiaju.png"]];
    cell.goods_name.attributedText = [self shadowstr:classCD.goods_name];
    cell.brand_name.attributedText = [self shadowstr:[NSString stringWithFormat:@"[%@] | %@", classCD.brand_name, classCD.style_name]];
    
    return cell;
}

- (NSMutableAttributedString *)shadowstr:(NSString *)string
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:string attributes:nil];
    NSShadow *shadow = [[NSShadow alloc]init];
    shadow.shadowColor = [UIColor grayColor];
    shadow.shadowOffset = CGSizeMake(1, 1);
    [str addAttributes:@{NSShadowAttributeName:shadow} range:NSMakeRange(0, str.length)];
    return str;
}

- (void)pushBuyVCAction:(UIButton *)btn
{
    NSInteger index = btn.tag - 100;
    
    ClassContentData *classCD = [self.goodDataArr objectAtIndex:index];
    BuyViewController *buyVC = [[BuyViewController alloc] init];
    buyVC.urlStr = classCD.buy_url;
//    [self.navigationController pushViewController:buyVC animated:YES];
    [self presentViewController:buyVC animated:YES completion:^{
        
    }];
    
}

- (void)dataHandler
{
    
    
    NSString *requestStr = [NSString stringWithFormat:@"http://www.meilele.com/solr_api/newjson/category-%@", self.pinyin];
    NSLog(@"=======%@", requestStr);
    self.goodDataArr = [NSMutableArray array];
    [AFRequdstAndLoad dataURLStr:requestStr datahand:^(id object) {
        
        if (object) {
            [_HUD removeFromSuperview];
        }
        
        NSArray *goodArr = [object objectForKey:@"goods_list"];
        for (NSDictionary *goodDic in goodArr) {
            ClassContentData *classCD = [[ClassContentData alloc] init];
            [classCD setValuesForKeysWithDictionary:goodDic];
            
            [self.goodDataArr addObject:classCD];
        }
        [self.tableV reloadData];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
